package netty.io.demo.Netty.udp.broadcast.bcside;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import netty.io.demo.Netty.udp.broadcast.LogConst;
import netty.io.demo.Netty.udp.broadcast.LogMsg;

import java.net.InetSocketAddress;

public class LogEventBroadcaster {
  private final EventLoopGroup group;
  private final Bootstrap bootstrap;
  
  public LogEventBroadcaster(InetSocketAddress inetSocketAddress) {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    
    bootstrap.group(group)
        // 设置 udp
        .channel(NioDatagramChannel.class)
        // 此参数 设置了广播模式
        .option(ChannelOption.SO_BROADCAST, true)
        // 设置 handler 事件
        .handler(new LogEventEncoder(inetSocketAddress));
  }
  
  public void run() throws InterruptedException {
    // 不需要 绑定本地地址
    Channel channel = bootstrap.bind(0).sync().channel();
    
    long count = 0;
    // 启动主处理循环，模拟日志发送
    for (; ; ) {
      channel.writeAndFlush(new LogMsg(null, ++count, LogConst.getLogInfo()));
      
      Thread.sleep(2000);
    }
  }
  
  public void stop() {
    group.shutdownGracefully();
  }
  
  public static void main(String[] args) throws InterruptedException {
    //创建并启动一个新的 UdpQuestionSide 的实例
    LogEventBroadcaster broadcaster = new LogEventBroadcaster(
        //表明本应用发送的报文并没有一个确定的目的地，也就是进行广播
        new InetSocketAddress("255.255.255.255",
            LogConst.MONITOR_SIDE_PORT));
    
    try {
      broadcaster.run();
    } finally {
      broadcaster.stop();
    }
  }
}
